package com.tentact.coolmeetingtest.dao;

import com.tentact.coolmeetingtest.support.RetMsg;
import com.tentact.coolmeetingtest.util.JDBCUtil;
import com.tentact.coolmeetingtest.util.OtherUtil;
import com.tentact.coolmeetingtest.vo.Room;

import java.sql.Timestamp;
import java.util.List;

/**
 * @author 星环
 * @date 2023/1/30 10:04:45
 * @description
 */
public class RoomDao {
    //public int
    public int addRoom(Room room){
        return (Integer) JDBCUtil.excute("insert into meeting_room values(null,?,?,?,?,?)", Integer.class,
                room.getRoomNumber(), room.getRoomName(), room.getPersonCount(), room.getState(), room.getNote());
    }

    public List<Room> selectAll() {
        return (List<Room>) JDBCUtil.excute("select * from meeting_room",Room.class);
    }
    public Room selectByNo(int roomno){
        List<Room> rooms = (List<Room>) JDBCUtil.excute("select * from meeting_room where roomno = ?", Room.class, roomno);
        return OtherUtil.getFirstDefaultNull(rooms);
    }

    public int updateRoomByRoomno(Room room) {
        return (Integer) JDBCUtil.excute(
                "update meeting_room set room_number = ?,room_name = ?,person_count = ?,state = ?,note = ? where roomno = ?",
                Integer.class,
                room.getRoomNumber(), room.getRoomName(), room.getPersonCount(),
                room.getState(), room.getNote(), room.getRoomno());

    }

    public Room selectAvalidSmallestRoom(Timestamp startTime, Timestamp endTime,int personCount) {
        List<Room> roomList = selectAvalidRoom(startTime, endTime, personCount);
        return OtherUtil.getFirstDefaultNull(roomList);
    }

        public List<Room> selectAvalidRoom(Timestamp startTime, Timestamp endTime,int personCount) {
        String sql = """
                SELECT * from meeting_room WHERE person_count > ? and roomno not in (
                              select DISTINCT roomno from meeting where
                              (start_time <= ? and end_time > ?) OR
                              (start_time >= ? and start_time < ?)
                              )
                order by person_count asc;
                """;
            return (List<Room>) JDBCUtil.excute(sql, Room.class, personCount,
                    startTime, startTime,
                    startTime, endTime );
        }
}
